package com.joizhang.seckill.controller;

import com.joizhang.seckill.api.service.UserService;
import com.joizhang.seckill.api.vo.LoginVo;
import com.joizhang.seckill.api.vo.UserVo;
import com.joizhang.seckill.utils.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.Objects;

import static com.joizhang.seckill.api.service.UserService.COOKIE_NAME_TOKEN;


@Controller
public class LoginController {

    private static final Logger log = LoggerFactory.getLogger(LoginController.class);

    @DubboReference
    private UserService userService;

    @RequestMapping("/")
    public String index(@CookieValue(value = "token", required = false) String token) {
        if (StringUtils.isEmpty(token)) {
            return "redirect:/login/to_login";
        }
        UserVo userVo = userService.getUserByTokenFromCache(token);
        if (Objects.isNull(userVo)) {
            return "redirect:/login/to_login";
        }
        return "redirect:/goods/to_list";
    }

    @RequestMapping("/login/to_login")
    public String toLogin() {
        return "login";
    }

    /**
     * 登录
     *
     * @param response 响应
     * @param loginVo  加入JSR303参数校验
     */
    @RequestMapping("/login/do_login")
    @ResponseBody
    public Result<String> doLogin(HttpServletResponse response, @Valid LoginVo loginVo) {
        String token = userService.userSignIn(loginVo);
        Cookie cookie = new Cookie(COOKIE_NAME_TOKEN, token);
        cookie.setHttpOnly(true);
        cookie.setMaxAge(3600 * 24 * 2);
        // 设置为网站根目录
        cookie.setPath("/");
        response.addCookie(cookie);
        return Result.success(token);
    }

}
